// 认证相关工具函数

export interface UserInfo {
  username: string;
  loginTime: string;
  token?: string;
}

export interface LoginResponse {
  token: string;
  user: {
    username: string;
    id: string;
    role: string;
  };
}

// 检查是否已登录
export const isLoggedIn = (): boolean => {
  return localStorage.getItem('isLoggedIn') === 'true';
};

// 获取用户信息
export const getUserInfo = (): UserInfo | null => {
  const userInfo = localStorage.getItem('userInfo');
  if (userInfo) {
    try {
      return JSON.parse(userInfo);
    } catch (error) {
      console.error('解析用户信息失败:', error);
      return null;
    }
  }
  return null;
};

// 设置登录状态
export const setLoginStatus = (userInfo: UserInfo): void => {
  localStorage.setItem('isLoggedIn', 'true');
  localStorage.setItem('userInfo', JSON.stringify(userInfo));
};

// 设置登录状态（包含token）
export const setLoginStatusWithToken = (loginResponse: LoginResponse): void => {
  const userInfo: UserInfo = {
    username: loginResponse.user.username,
    loginTime: new Date().toISOString(),
    token: loginResponse.token
  };
  
  localStorage.setItem('isLoggedIn', 'true');
  localStorage.setItem('userInfo', JSON.stringify(userInfo));
  localStorage.setItem('authToken', loginResponse.token);
  localStorage.setItem('userId', loginResponse.user.id);
  localStorage.setItem('userRole', loginResponse.user.role);
};

// 清除登录状态
export const clearLoginStatus = (): void => {
  localStorage.removeItem('isLoggedIn');
  localStorage.removeItem('userInfo');
  localStorage.removeItem('authToken');
  localStorage.removeItem('userId');
  localStorage.removeItem('userRole');
};

// 检查登录状态是否过期（24小时）
export const isLoginExpired = (): boolean => {
  const userInfo = getUserInfo();
  if (!userInfo) return true;
  
  const loginTime = new Date(userInfo.loginTime);
  const now = new Date();
  const diffInHours = (now.getTime() - loginTime.getTime()) / (1000 * 60 * 60);
  
  return diffInHours > 24;
};

// 自动登出过期用户
export const checkAndClearExpiredLogin = (): boolean => {
  if (isLoggedIn() && isLoginExpired()) {
    clearLoginStatus();
    return true;
  }
  return false;
};

// 获取保存的用户凭据
export const getSavedCredentials = (): { username: string; password: string; saveTime: string } | null => {
  const credentials = localStorage.getItem('userCredentials');
  if (credentials) {
    try {
      return JSON.parse(credentials);
    } catch (error) {
      console.error('解析保存的凭据失败:', error);
      return null;
    }
  }
  return null;
};

// 清除保存的用户凭据
export const clearSavedCredentials = (): void => {
  localStorage.removeItem('userCredentials');
};

// 获取认证token
export const getAuthToken = (): string | null => {
  return localStorage.getItem('authToken');
};

// 获取用户ID
export const getUserId = (): string | null => {
  return localStorage.getItem('userId');
};

// 获取用户角色
export const getUserRole = (): string | null => {
  return localStorage.getItem('userRole');
};

// 检查token是否存在
export const hasValidToken = (): boolean => {
  const token = getAuthToken();
  return token !== null && token.length > 0;
};
